from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config

db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = 'auth.login'
# 删除重复的登录提示信息
# login.login_message = '请先登录以访问此页面。'

# 添加user_loader回调函数
@login.user_loader
def load_user(id):
    from app.models import User
    return User.query.get(int(id))

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    
    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp)
    
    from app.admin import bp as admin_bp
    app.register_blueprint(admin_bp)
    
    # 添加初始化默认用户的功能
    with app.app_context():
        from app.models import User
        db.create_all()
        
        # 检查是否已存在默认管理员用户
        default_admin_username = app.config.get('DEFAULT_ADMIN_USERNAME', 'admin')
        default_admin = User.query.filter_by(username=default_admin_username).first()
        
        if not default_admin:
            # 创建默认管理员账户
            admin = User(
                username=default_admin_username,
                email=app.config.get('DEFAULT_ADMIN_EMAIL', 'admin@example.com')
            )
            admin.set_password(app.config.get('DEFAULT_ADMIN_PASSWORD', 'admin'))
            db.session.add(admin)
            db.session.commit()
    
    return app